#ifndef MY_WIFI_H
#define MY_WIFI_H

#include <WiFi.h>
#include <ArduinoJson.h>
#include "cJSON.h"
#include <HTTPClient.h>


String get_tok = "https://aip.baidubce.com/oauth/2.0/token";
String image_request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/request";
String image_request_get_url="https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/get-result";

const char* client_id = "3oMteoBBwRa0SCUEWy5AevkO";
const char* client_secret = "hoZAD2Poxm66OStUnTUy1FrToa5DFHiW";
String acs_tok = "24.c333e3d7f09a248619476f68cb689a1a.2592000.1731165869.282335-46332156" ;

#define bufferLen 50000
char data_json[bufferLen];

void image_get_tok()  //获取tok码
{ 
  HTTPClient http_get_tok ;
  http_get_tok.setTimeout(20000);
  //"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=3oMteoBBwRa0SCUEWy5AevkO&client_secret=hoZAD2Poxm66OStUnTUy1FrToa5DFHiW"
  String my_get_tok = get_tok + "?grant_type=client_credentials&client_id=" + String(client_id) + "&client_secret=" +  String(client_secret) ;
  http_get_tok.begin(my_get_tok);
  String body = "{}";
  int httpResponseCode = http_get_tok.POST(body);
  if(httpResponseCode == 200)
  {
     String response = http_get_tok.getString();
     http_get_tok.end();
     StaticJsonDocument<1024> json1;
     deserializeJson(json1,response);
     String get_acs_tok  = json1["access_token"];
     //Serial.println(get_acs_tok);
     acs_tok = get_acs_tok;
  }
  else
  {
    http_get_tok.end();
    //Serial.println("no get tok");
  }
}

String image_request(String change) //发送请求，返回的是请求结果代码，该码要填入下一个函数中（change是图片数据（jpg）
{
  memset(data_json, '\0', strlen(data_json)); //清空数组
  strcat(data_json, "{");
  strcat(data_json, "\"image\":\"");
  change.replace("\r\n","");
  strcat(data_json,change.c_str());  //base64编码数据
  strcat(data_json, "\",");
  strcat(data_json, "\"prompt\":\"你看见了什么\",");                                                                    
  strcat(data_json, "}");                                                                      
  HTTPClient http_image_request ;
  http_image_request.setTimeout(20000);
  String my_image_request = image_request_url +"?access_token=" +acs_tok ;
  http_image_request.begin(my_image_request);
  http_image_request.addHeader("Content-Type", "application/json");
   int httpCode =  http_image_request.POST(data_json);
  if (httpCode == 200)
  {

      String  response = http_image_request.getString();
      http_image_request.end();
       DynamicJsonDocument jsonDoc(1024);
       deserializeJson(jsonDoc, response);
      Serial.println(response);
       String id = jsonDoc["result"];
       return id ;
  }
    else {
      Serial.println("error");
      http_image_request.end();
      return "error" ;
    }

}


#endif 